package Matrix;

import java.util.ArrayList;
import java.util.List;

/**
 * 54.螺旋矩阵
 * 给你一个 m 行 n 列的矩阵 matrix ，请按照 顺时针螺旋顺序 ，返回矩阵中的所有元素。
 */
public class spiralOrder {
    /**
     * hot100一刷
     */
    public class SpiralOrder {
        public List<Integer> spiralOrder(int[][] matrix) {
            List<Integer> result = new ArrayList<>();

            // 处理空矩阵
            if (matrix == null || matrix.length == 0 || matrix[0].length == 0) {
                return result;
            }

            int rows = matrix.length;
            int cols = matrix[0].length;
            int left = 0, right = cols-1;
            int top = 0, bottom = rows-1;

            while (left <= right && top <= bottom) {
                // 从左到右
                for (int j = left; j <= right && top <= bottom; j++) {
                    result.add(matrix[top][j]);
                }
                top++;

                // 从上到下
                for (int i = top; i <= bottom && left <= right; i++) {
                    result.add(matrix[i][right]);
                }
                right--;

                // 从右到左
                for (int j = right; j >= left && top <= bottom; j--) {
                    result.add(matrix[bottom][j]);
                }
                bottom--;

                // 从下到上
                for (int i = bottom; i >= top && left <= right; i--) {
                    result.add(matrix[i][left]);
                }
                left++;
            }

            return result;
        }
    }


    /**
     * hot100二刷
     */
    class Solution {
        public List<Integer> spiralOrder(int[][] matrix) {
            int m = matrix.length;
            int n = matrix[0].length;
            List<Integer> res = new ArrayList<>();
            int startRow = 0;
            int endRow = m - 1;
            int startCol = 0;
            int endCol = n - 1;

            while (startRow <= endRow && startCol <= endCol) {
                for (int i = startCol; i <= endCol && startRow <= endRow; i++) {
                    res.add(matrix[startRow][i]);
                }
                startRow++;
                for (int i = startRow; i <= endRow && startCol <= endCol; i++) {
                    res.add(matrix[i][endCol]);
                }
                endCol--;
                for (int i = endCol; i >= startCol && startRow <= endRow; i--) {
                    res.add(matrix[endRow][i]);
                }
                endRow--;
                for (int i = endRow; i >= startRow && startCol <= endCol; i--) {
                    res.add(matrix[i][startCol]);
                }
                startCol++;
            }
            return res;

        }
    }


}
